<template>
  <div class="app-container">
    <!-- 顶部控制台 -->
    <div class="filter-container">
      <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleOpenSavePage">添加角色</el-button>
    </div>
    <!-- 页面数据列表 -->
    <div class="data-table">
      <el-table :data="responseData.tableList"
                border style="width: 100%;"
                v-loading="pageData.loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :header-cell-style="{ background: '#545C64', color: '#ffffff' }"
                @selection-change="handleTableSelection">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column fixed="left" prop="adminId" label="角色ID" width="280" align="center"/>
        <el-table-column prop="adminName" label="角色名称" width="180" align="center"/>
        <el-table-column prop="adminAccount" label="角色账号" width="180" align="center"/>
        <el-table-column prop="adminLevel" label="角色等级" width="120" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.adminLevel === 3"><el-tag type="info">操作员</el-tag></span>
            <span v-if="scope.row.adminLevel === 2"><el-tag type="success">管理员</el-tag></span>
            <span v-if="scope.row.adminLevel === 1"><el-tag type="primary">超级管理员</el-tag></span>
          </template>
        </el-table-column>
        <el-table-column prop="adminRole" label="父级路由" width="320" align="center">
          <template slot-scope="scope">
            <el-popover v-if="null != scope.row.adminRoleStr && scope.row.adminRoleStr != ''" trigger="hover" placement="top">
              <span v-for="item in scope.row.adminRoleStr.split(',')">
                <el-tag type="success" v-if="item !== ''">{{item}}</el-tag>
              </span>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.adminRoleStr.split(',')[0] }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="adminRole" label="子集路由" width="320" align="center">
          <template slot-scope="scope">
            <el-popover v-if="null != scope.row.adminRoleChildStr && scope.row.adminRoleChildStr != ''" trigger="hover" placement="top">
              <span v-for="item in scope.row.adminRoleChildStr.split(',')">
                <el-tag type="primary" v-if="item !== ''">{{item}}</el-tag>
              </span>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.adminRoleChildStr.split(',')[0] }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="adminPermission" label="操作权限" width="320" align="center">
          <template slot-scope="scope">
            <el-popover v-if="null != scope.row.adminPermissionStr && scope.row.adminPermissionStr != ''" trigger="hover" placement="top">
              <span v-for="item in scope.row.adminPermissionStr.split(',')">
                <el-tag type="primary" v-if="item !== ''">{{item}}</el-tag>
              </span>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.adminPermissionStr.split(',')[0] }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="adminDescription" label="用户签名" width="120" align="center"/>
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleOpenUpdatePage(scope)">编辑</el-button>
            <el-button v-if="scope.row.adminStatus == 0" size="mini" type="success" @click="handleUpdateDataStatus(scope,1)">发布</el-button>
            <el-button v-if="scope.row.adminStatus == 1" size="mini" type="info" @click="handleUpdateDataStatus(scope,0)">下架</el-button>
            <el-button type="danger" size="mini"  @click="handleDeleteData(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页器-->
    <div style="margin-top: 20px">
      <div class="block" style="width: 100%; text-align: center">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="form.pageNum"
          :page-size="form.pageSize"
          :total="form.total"
          :page-sizes="[12, 50, 100, 200]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>
    <!--角色新增隐藏域-->
    <div style="width: 60%; margin: auto">
      <el-dialog :title="pageData.formPanelTitle" :visible.sync="pageData.formPanelStatus" size="small"
                 :before-close="handleCloseSavePage">
        <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
          <el-form-item label="登录账号" prop="adminAccount">
            <el-input v-model="form.adminAccount"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="adminPassword">
            <el-input v-model="form.adminPassword"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="adminPhone">
            <el-input v-model="form.adminPhone"></el-input>
          </el-form-item>
          <el-form-item label="角色等级">
            <el-radio-group v-model="form.adminLevel" size="medium">
              <el-radio-button :label="3">操作员</el-radio-button>
              <el-radio-button :label="2">管理员</el-radio-button>
              <el-radio-button :label="1">超级管理员</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-radio-group v-model="form.adminStatus" size="medium">
              <el-radio :label="1">发布</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="父级路由">
            <el-checkbox-group v-model="form.adminRole" size="medium" @change="handleChooseRouter">
              <el-checkbox v-for="(item, index) in responseData.routerList" :label="item.value" :key="index" style="margin-left: 6px">{{item.label}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="子集路由">
            <el-checkbox-group v-model="form.adminRoleChild" size="medium" @change="handleChooseChildRouter">
              <el-checkbox v-for="(item, index) in responseData.routerChildList" :label="item.value" :key="index" style="margin-left: 6px">{{item.label}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="操作权限">
            <el-checkbox-group v-model="form.adminPermission" size="medium">
              <el-checkbox v-for="(item, index) in responseData.routerPermissionList" :label="item.value" :key="index" style="margin-left: 6px">{{item.label}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="用户昵称" prop="adminName">
            <el-input v-model="form.adminName"></el-input>
          </el-form-item>
          <el-form-item label="用户签名">
            <el-input v-model="form.adminDescription" type="textarea" :rows="2"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSaveButtonClick('form')">保存角色</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission } from '@/utils/UserCookies';

  import { loadCmsCharacterList,loadCmsRouterList,loadCmsRouterChildList,loadCmsPermissionList,
    saveCmsCharacterData,updateCmsCharacterData,updateCmsCharacterStatus,deleteCmsCharacterData } from "@/api/system";
  export default {
    name: "character",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      return {
        pageData:{
          loading: false,// 页面加载状态
          formPanelStatus: false,// 新增/修改隐藏域展示状态
          formPanelTitle: "添加角色",// 新增/修改隐藏域标题
          formPanelType: 0
        },// 页面配置数据
        form:{
          pageNum: 1,// 表单--页码
          pageSize: 12,// 表单--页面
          total: 0,// 表单--总量
          adminId: "",// 表单--用户ID
          adminAccount: "",// 表单--登录账号
          adminPassword: "",// 表单--登录密码
          adminPhone: "",// 表单--注册手机号
          adminLevel: 0,// 表单--用户角色
          adminRole: [],// 表单--父级菜单权限
          adminRoleChild: [],// 表单--子级菜单权限
          adminPermission: [],// 表单--操作权限
          adminName: "",// 表单--姓名
          adminDescription: "",// 表单--描述
          adminStatus: 0,// 表单--可用状态
          selection: []// 多选的内容
        },// 页面表单
        formRules: {
          adminAccount: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === ''){
                  this.$message.warning("请输入登录账号");
                  callback(new Error('请输入登录账号'));
                } else {
                  callback();
                }
              }, trigger: "blur"}
          ],// 登录账号验证
          adminPassword: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === ''){
                  this.$message.warning("请输入登录密码");
                  callback(new Error('请输入登录密码'));
                } else {
                  callback();
                }
              }, trigger: "blur"}
          ],// 登录密码验证
          adminPhone: [
            {
              required: true,
              validator: (rule, value, callback) => {
                const regex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/gm;
                if (value.search(regex)){
                  this.$message.warning("请输入正确的手机号");
                  callback(new Error('请输入正确的手机号'));
                } else {
                  callback();
                }
              }, trigger: "blur"}
          ],// 手机号验证
          adminName: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value === ''){
                  this.$message.warning("请输入用户昵称");
                  callback(new Error('请输入用户昵称'));
                } else {
                  callback();
                }
              }, trigger: "blur"}
          ],// 登录姓名验证
        },// 表单验证
        responseData: {
          tableList: [],// 接口返回数据--表格列表
          routerList: [],// 接口返回数据--父级菜单列表
          routerChildList: [],// 接口返回数据--子级菜单列表
          routerPermissionList: [],// 接口返回数据--操作权限列表
        },// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods:{
      // 事件函数
      handlePageInit(){
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsCharacterList();// 读取路由角色列表
      },// 页面初始化事件
      handleCurrentChange(val){
        this.form.pageNum = val;// 更换页码
        this.handlePageInit();// 进行数据加载
      },// 页码切换事件
      handleSizeChange(val){
        this.form.pageSize = val;// 更换页面大小
        this.handlePageInit();// 进行数据加载
      },// 页面size切换事件
      handleTableSelection(val){
        let routerList = [];// 初始化多选数组
        for (let i=0; i<val.length; i++){
          routerList.push(val[i].routerId);
        }// 遍历多选的列表，将ID拼入数组中
        this.form.selection = routerList;// 进行多选值的切换
      },// 表格多选事件
      handleOpenSavePage(){
        // 判断当前登录用户所拥有的的操作权限
        if (PermissionsToDetectFormUser(getPermission(), "20001")){
          // 拥有对应权限，首先清除对应表单，打开隐藏面板
          this.pageData.formPanelType = 1;// 新增页面
          this.form.adminAccount = "";
          this.form.adminPassword = "";
          this.form.adminPhone = "";
          this.form.adminLevel = 0;
          this.form.adminRole = [];
          this.form.adminRoleChild = [];
          this.form.adminPermission = [];
          this.form.adminName = "";
          this.form.adminDescription = "";
          this.form.adminStatus = 0;
          this.pageData.formPanelStatus = true;
          this.pageData.formPanelTitle = "新增角色";
          // 读取父级菜单预设列表
          this.loadCmsRouterList();
        } else {
          // 当前权限不足，不执行操作，给与相应提示
          this.$message.warning("您的权限不足，无法使用此功能，请联系管理员");
        }
      },// 打开新增角色面板
      handleOpenUpdatePage(scope){
        // 判断当前登录用户所拥有的的操作权限
        if (PermissionsToDetectFormUser(getPermission(), "20003")){
          // 当前操作权限充足，进行相应操作
          this.pageData.formPanelType = 2;// 新增页面
          this.form.adminId = scope.row.adminId;
          this.form.adminAccount = scope.row.adminAccount;
          this.form.adminPassword = scope.row.adminPassword;
          this.form.adminPhone = scope.row.adminPhone;
          this.form.adminLevel = scope.row.adminLevel;
          this.form.adminName = scope.row.adminName;
          this.form.adminDescription = scope.row.adminDescription;
          this.form.adminStatus = scope.row.adminStatus;
          let adminRoleArray = [];// 父级菜单
          scope.row.adminRole.split(",").forEach(item => {
            adminRoleArray.push(item);
          });
          this.form.adminRole = adminRoleArray;
          let adminRoleChildArray = [];// 子集菜单
          scope.row.adminRoleChild.split(",").forEach(item => {
            adminRoleChildArray.push(item);
          });
          this.form.adminRoleChild = adminRoleChildArray;
          let adminPermissionArray = [];// 权限菜单
          scope.row.adminPermission.split(",").forEach(item => {
            adminPermissionArray.push(item);
          });
          this.form.adminPermission = adminPermissionArray;
          // 读取父级菜单预设列表
          this.loadCmsRouterList();
          // 模拟点击父级菜单
          this.handleChooseRouter();
          // 模拟点击子级菜单
          this.handleChooseChildRouter();
          this.pageData.formPanelStatus = true;
          this.pageData.formPanelTitle = "修改角色";
        } else {
          // 当前权限不足，不执行操作，给与相应提示
          this.$message.warning("您的权限不足，无法使用此功能，请联系管理员");
        }
      },// 打开角色修改面板
      handleCloseSavePage(){
        this.$confirm("确认关闭？").then(response => {
          this.pageData.formPanelStatus = false;
          this.pageData.formPanelTitle = "";
          this.pageData.formPanelType = 0;// 新增页面
          this.form.adminId = "";
          this.form.adminAccount = "";
          this.form.adminPassword = "";
          this.form.adminPhone = "";
          this.form.adminLevel = 0;
          this.form.adminRole = [];
          this.form.adminRoleChild = [];
          this.form.adminPermission = [];
          this.form.adminName = "";
          this.form.adminDescription = "";
          this.form.adminStatus = 0;
        }).catch(err => {
          console.log(err);
        });
      },// 弹窗面板关闭监听，避免出现误点击操作数据丢失
      handleChooseRouter(){
        this.loadCmsRouterChildList();// 获取二级菜单列表
      },// 选中父级菜单事件
      handleChooseChildRouter(){
        this.loadCmsPermissionList();// 获取三级权限列表
      },// 选中子级菜单事件
      handleSaveButtonClick(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.pageData.formPanelType === 1) {// 新增接口调用
              // 判断当前登录用户所拥有的的操作权限
              if (PermissionsToDetectFormUser(getPermission(), "20001")){
                // 当前操作权限充足，进行敏感操作提示
                this.$confirm("此操作将保存当前所填写的角色信息，请核对后继续, 是否继续?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }).then(() => {
                  // 同一操作，执行具体流程
                  this.saveCmsCharacterData();
                }).catch(close => {
                  console.log(close);
                  this.$message.info("已取消操作");
                });
              } else {
                // 当前权限不足，不执行操作，给与相应提示
                this.$message.warning("您的权限不足，无法使用此功能，请联系管理员");
              }
            } else {// 修改接口调用
              // 判断当前登录用户所拥有的的操作权限
              if (PermissionsToDetectFormUser(getPermission(), "20003")){
                // 当前操作权限充足，进行敏感操作提示
                this.$confirm("此操作将保存当前所填写的角色信息，请核对后继续, 是否继续?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }).then(() => {
                  // 同一操作，执行具体流程
                  this.updateCmsCharacterData();
                }).catch(close => {
                  console.log(close);
                  this.$message.info("已取消操作");
                });
              } else {
                // 当前权限不足，不执行操作，给与相应提示
                this.$message.warning("您的权限不足，无法使用此功能，请联系管理员");
              }
            }
          } else {
            return false
          }
        })
      },// 保存按钮点击事件
      handleUpdateDataStatus(scope, status){
        if (PermissionsToDetectFormUser(getPermission(), "20005")){
          // 当前操作权限充足，进行敏感操作提示
          this.$confirm("此操作将更改当前所选角色信息的发布状态，有可能导致当前账号无法登陆，请核对后继续, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            // 同一操作，执行具体流程
            let param = {
              adminId: scope.row.adminId,
              adminStatus: status
            };
            this.updateCmsCharacterStatus(param);
          }).catch(close => {
            console.log(close);
            this.$message.info("已取消操作");
          });
        } else {
          // 当前权限不足，不执行操作，给与相应提示
          this.$message.warning("您的权限不足，无法使用此功能，请联系管理员");
        }
      },// 更新角色发布状态
      handleDeleteData(scope){
        if (scope.row.adminStatus === 1){
          this.$message.warning("已发布的角色无法进行删除，如需删除，请先下架");
        } else {
          if (PermissionsToDetectFormUser(getPermission(), "20002")){
            // 当前操作权限充足，进行敏感操作提示
            this.$confirm("此操作将删除当前所选角色信息，请核对后继续, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              // 同一操作，执行具体流程
              let param = {
                adminId: scope.row.adminId
              };
              this.deleteCmsCharacterData(param);
            }).catch(close => {
              console.log(close);
              this.$message.info("已取消操作");
            });
          } else {
            // 当前权限不足，不执行操作，给与相应提示
            this.$message.warning("您的权限不足，无法使用此功能，请联系管理员");
          }
        }
      },// 删除按钮点击事件

      // 接口
      loadCmsCharacterList(){
        this.form.adminRole = this.form.adminRole.toString();
        this.form.adminRoleChild = this.form.adminRoleChild.toString();
        this.form.adminPermission = this.form.adminPermission.toString();
        loadCmsCharacterList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            this.responseData.tableList = response.data.list;
            this.form.total = response.data.total;
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取角色管理页面数据列表
      loadCmsRouterList(){
        loadCmsRouterList().then(response => {
          if (response.code === '200'){
            this.responseData.routerList = response.data;
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取角色新增/修改页可选父级菜单列表
      loadCmsRouterChildList(){
        let form = JSON.parse(JSON.stringify(this.form));
        form.adminRole = form.adminRole.toString();
        form.adminRoleChild = form.adminRoleChild.toString();
        form.adminPermission = form.adminPermission.toString();
        loadCmsRouterChildList(form).then(response => {
          if (response.code === '200'){
            this.responseData.routerChildList = response.data;
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取角色新增/修改页可选子级菜单列表
      loadCmsPermissionList(){
        let form = JSON.parse(JSON.stringify(this.form));
        form.adminRole = form.adminRole.toString();
        form.adminRoleChild = form.adminRoleChild.toString();
        form.adminPermission = form.adminPermission.toString();
        loadCmsPermissionList(form).then(response => {
          if (response.code === '200'){
            this.responseData.routerPermissionList = response.data;
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取角色新增/修改页操作权限列表
      saveCmsCharacterData(){
        let form = JSON.parse(JSON.stringify(this.form));
        form.adminRole = form.adminRole.toString();
        form.adminRoleChild = form.adminRoleChild.toString();
        form.adminPermission = form.adminPermission.toString();
        saveCmsCharacterData(form).then(response => {
          if (response.code === '200'){
            this.$message.success("角色新增成功");
            this.pageData.formPanelStatus = false;
            this.pageData.formPanelTitle = "新增角色";
            this.pageData.formPanelType = 0;// 新增页面
            this.form.adminId = "";
            this.form.adminAccount = "";
            this.form.adminPassword = "";
            this.form.adminPhone = "";
            this.form.adminLevel = 0;
            this.form.adminRole = [];
            this.form.adminRoleChild = [];
            this.form.adminPermission = [];
            this.form.adminName = "";
            this.form.adminDescription = "";
            this.form.adminStatus = 0;
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 保存后台登录用户
      updateCmsCharacterData(){
        let form = JSON.parse(JSON.stringify(this.form));
        form.adminRole = form.adminRole.toString();
        form.adminRoleChild = form.adminRoleChild.toString();
        form.adminPermission = form.adminPermission.toString();
        updateCmsCharacterData(form).then(response => {
          if (response.code === '200'){
            this.$message.success("角色新增成功");
            this.pageData.formPanelStatus = false;
            this.pageData.formPanelTitle = "新增角色";
            this.pageData.formPanelType = 0;// 新增页面
            this.form.adminId = "";
            this.form.adminAccount = "";
            this.form.adminPassword = "";
            this.form.adminPhone = "";
            this.form.adminLevel = 0;
            this.form.adminRole = [];
            this.form.adminRoleChild = [];
            this.form.adminPermission = [];
            this.form.adminName = "";
            this.form.adminDescription = "";
            this.form.adminStatus = 0;
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 更新后台登录用户
      updateCmsCharacterStatus(param){
        updateCmsCharacterStatus(param).then(response => {
          if (response.code === "200"){
            this.$message.success(param.adminStatus === 1 ? "发布成功" : "下架成功");
            this.handlePageInit();
          } else {
            this.$message.warning("操作失败")
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },
      deleteCmsCharacterData(param){
        deleteCmsCharacterData(param).then(response => {
          if (response.code === "200"){
            this.$message.success("删除成功");
            this.handlePageInit();
          } else {
            this.$message.warning("操作失败")
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function () {
      let _this = this;
      setTimeout(function () {
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped></style>
